#!/bin/bash

set -e

CUR_DIR=$PWD
SRC_DIR=$PWD
cmd=$1

export GOPROXY=https://goproxy.io
export GOPATH=/usr/local/go/goPath
export GOBIN=$GOPATH/bin

PKG_LIST=$(go list ./... | grep -v /vendor/)
LINT_VER=v0.0.0-20190409202823-959b441ac422


# Code coverage generation
function coverage_test(){
    COVERAGE_DIR="${COVERAGE_DIR:-coverage}"
    mkdir -p "$COVERAGE_DIR";
    for package in ${PKG_LIST}; do
        go test  -covermode=count -coverprofile "${COVERAGE_DIR}/${package##*/}.temp" "$package" ;
    done ;
    echo 'mode: count' > "${COVERAGE_DIR}"/coverage.cov ;
    tail -q -n +2 "${COVERAGE_DIR}"/*.temp >> "${COVERAGE_DIR}"/coverage.cov ;
    go tool cover -func="${COVERAGE_DIR}"/coverage.cov ;
    if [ "$1" == "html" ]; then
        go tool cover -html="${COVERAGE_DIR}"/coverage.cov -o coverage.html ;
    fi
    rm -rf "$COVERAGE_DIR";
}

case $cmd in
    lint) $0 dep && $GOBIN/golint -set_exit_status ${PKG_LIST} ;;
    test) go test  -short ${PKG_LIST} ;;
    race) $0 dep && go test  -race -short ${PKG_LIST} ;;
    coverage) coverage_test ;;
    coverhtml) coverage_test html ;;
    dep) go get -v golang.org/x/lint@$LINT_VER && cd $GOPATH/pkg/mod/golang.org/x/lint@$LINT_VER/ && go install ./... && cd $CUR_DIR ;;
    bak)
      if [ -e "/app/yw/transfer-service/transfer-service" ]; then
                  sudo rm -f /app/yw/transfer-service/transfer-service.bak && mv /app/yw/transfer-service/transfer-service /app/yw/transfer-service/transfer-service.bak
              else
                  echo "Source file does not exist. No backup performed."
              fi
              ;;
    swag) swag i --parseDependency --parseInternal ;;
    build)
        $0 bak
        go mod tidy
        cd $SRC_DIR/cmd/template
        go build -o transfer-service
        mv ./transfer-service /app/yw/transfer-service/
        ;;
    deploy) supervisorctl restart transfer-service ;;
    clean) rm -rf ${PKG_LIST} && git checkout . ;;
esac

cd $CUR_DIR
